from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
import sys, os
import traceback

# Local imports
from computer.windowsxpconfiguration import WindowsXPConfiguration

GPOFILENAME = u'gpo.conf'

class UGPClientProtocol(Protocol):
	def dataReceived(self, data):
		print "Received: ", data
		idx = data.find( 'GPO VERSION = ' )
		if idx > -1:
			version = data[len(data)-1:len(data)]
			if not self.checkGPOVersion(version):
				self.transport.write("GET GPO FILE")
		if data.find( u'<!--GPO FILE-->\n' ) > -1:
			print data.find( u'<!--GPO FILE-->\n' )
			print "Receiving data: ", data
			self.writeGPOFile(data)

	def writeGPOFile(self, data):
		# The server are sending the file
		fp = open("gpo.conf", 'w')
		print data
		fp.write(data)
		fp.close()
		print "GPO File Updated!"
	
	def connectionMade(self):
		self.transport.write("GET CONFIG VERSION")
		
		#if not self.checkGPOFile():
			# Get the file
		#	self.transport.write("GET GPO FILE")
		#	print "Send GET GPO FILE"
	
	def checkGPOFile(self):
		wxpConf = WindowsXPConfiguration()
		gpoFile = wxpConf.getCurrentUserHome() + '\\' + GPOFILENAME
		try:
			print gpoFile
			fp = open(gpoFile)
		except IOError, ex:
			return False
		except Exception, ex:
			exc_type, exc_value, exc_traceback = sys.exc_info()
			traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
			return False
		return True
	
	def checkGPOVersion( self, version ):
		
		if not self.checkGPOFile():
			return False
		
		# TODO: Check the version file
		
		return True

class UGPClientFactory(ClientFactory):
	def startedConnecting(self, connector):
		print 'Started to connect.'
		
	def buildProtocol(self, addr):
		print 'Connected.'
		return UGPClientProtocol()
		
	def clientConnectionLost(self, connector, reason):
		print 'Lost connection. Reason:', reason
		
	def clientConnectionFailed(self, connector, reason):
		print 'Connection failed. Reason:', reason



HOST, PORT = "161.111.168.222", 4699
data = " ".join(sys.argv[1:])

# Configure the agent
print "Executing main"
reactor.connectTCP(HOST, PORT, UGPClientFactory())

# Connect
reactor.run()
